import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import baseApi from "./config"
const ContentType = {
  JSON: 'application/json;charset=UTF-8',
  FORM: 'application/x-www-form-urlencoded;charset=UTF-8',
  UPLOAD: 'multipart/form-data'
}

const service = axios.create({
  baseURL: baseApi.HOST,
  timeout: 10000,
  headers: {
    'Content-Type': ContentType.JSON, // 设置默认请求头
  }
})

service.interceptors.request.use(
  config => {
    const chatToken = localStorage.getItem("chatToken")
    if(chatToken) {
      config.headers["Authorization"] = "Bearer " + chatToken
      config.headers["chatToken"] = "2b18ac5a7b9ea28ddbbc0db3837b7fc1"
    }
    if(config.data) {
      if(config.headers["Content-Type"] === ContentType.FORM) {
        config.data = qs.stringify(config.data)
      }
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if(response.headers["file-name"]) {
      return response
    }
    // if(response.data.code !== 100000) {
    //   ElMessage.error(response.data.msg)
    // }
    return response.data || null

  }
)

export default service